package com.project.class4_7;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RWTest {
    //创建读写锁对象
    private ReentrantReadWriteLock rwlock=new ReentrantReadWriteLock();
    private Lock lock= rwlock.readLock();
    public void read1(){
        //加读锁
        rwlock.readLock().lock();
        try{
        for (int i=0;i<10;i++){
            System.out.println("读锁"+Thread.currentThread()+"   "+i);

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }}finally {
            rwlock.readLock().unlock();
        }
    }

    public void read2(){
        //加读锁
        rwlock.readLock().lock();
        try{
            for (int i=0;i<10;i++){
                System.out.println("du锁"+Thread.currentThread()+"   "+i);

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }}finally {
            rwlock.readLock().unlock();
        }
    }

    public void write(){
        //加写锁
        rwlock.writeLock().lock();
        try{
            for (int i=0;i<10;i++){
                System.out.println("写锁"+Thread.currentThread()+"   "+i);

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }}finally {
            rwlock.writeLock().unlock();
        }
    }
}
